/*
 * @Author: liwenhao
 * @Date: 2021-05-24 22:02:11
 * @LastEditors: lwHao
 * @LastEditTime: 2021-05-25 14:39:02
 * @Description:
 */
const fs = require('fs')
const path = require('path')
const dirPath = path.resolve()
console.log('计算大小所在目录:', dirPath);
function calSizeAsync(dir) {
  let size = 0
  function run(dirPath, cb) {
    fs.stat(dirPath, (err, statObj) => {
      if (statObj.isFile()) {
        size += statObj.size
        cb && cb()
      } else {
        runList(dirPath, () => {
          cb && cb()
        })
      }
    })
  }
  function runList(dirPath, cb) {
    fs.readdir(dirPath, (err, files) => {
      let i = 0
      if (files.length === 0) {
        return cb && cb()
      }
      files.forEach(file => {
        run(path.resolve(dirPath, file), () => {
          i++
          if (i === files.length) {
            cb && cb()
          }
        })
      })
    })
  }
  run(dir, () => {
    console.log('异步获取文件总大小为:', size);
  })
}

calSizeAsync(dirPath)

/**
 * 同步获取文件总大小
 * @param {} dirPath 
 */
function calSizeSync(dirPath) {
  let size = 0
  function run(dirPath) {
    let statObj = fs.statSync(dirPath)
    if (statObj.isFile()) {
      size += statObj.size
    } else {
      let files = fs.readdirSync(dirPath)
      files.forEach(file => {
        run(path.resolve(dirPath, file))
      })
    }
  }
  run(dirPath)
  console.log('同步获取文件总大小为:', size);
}

calSizeSync(dirPath)
